<?php

/**
 * This is the model class for table "topic".
 *
 * The followings are the available columns in table 'topic':
 * @property integer $id
 * @property string $title
 * @property string $content
 * @property integer $categoryId
 * @property integer $status
 * @property integer $createTime
 */
class Topic extends CActiveRecord
{
        public $upload;
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Topic the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'topic';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('title, content, categoryId', 'required'),
			array('title', 'length', 'max'=>255),
                        array('status, imageId', 'safe'),
                        array('upload', 'file', 'types' => 'jpg, gif, png, doc, docx, xls, xlsx, zip, rar, pdf', 'allowEmpty' => TRUE),
			array('id, title, content, categoryId, status', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
                    'avatar'=>array(self::BELONGS_TO, 'FileImage', 'imageId'),
                    'category'=>array(self::BELONGS_TO, 'TopicCategory', 'categoryId'),
                    'attachment'=>array(self::HAS_ONE, 'File', 'contentId', 'condition'=>'attachment.contentType='.File::TYPE_TOPIC)
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'title' => Yii::t('main', 'Title'),
			'content' => Yii::t('main', 'Content'),
			'categoryId' => Yii::t('main', 'Category'),
			'status' => Yii::t('main', 'Status'),
                        'upload'=>Yii::t('main', 'Attach File'),
                        'imageId'=>Yii::t('main', 'Thumbnail')
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('title',$this->title,true);
		$criteria->compare('content',$this->content,true);
		$criteria->compare('categoryId',$this->categoryId);
		$criteria->compare('status',$this->status);
                $criteria->order='id desc';

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
                        'pagination'=>array(
                            'pageSize'=>10
                        )
		));
	}
        
        protected function beforeSave() {
            $this->createTime=time();
            return parent::beforeSave();
        }

        protected function afterSave() {
            if ($this->upload) {
                $fileModel=new File;

                $fileName = $this->upload->name;
                $fol=date('Ymd');
                $uploadFolder = Yii::getPathOfAlias('webroot') . DIRECTORY_SEPARATOR . 'files' . DIRECTORY_SEPARATOR . $fol;
                if (!is_dir($uploadFolder)) {
                    mkdir($uploadFolder, 0755, TRUE);
                }

                $fileName = preg_replace('/[^\w\._]+/', '_', $fileName);

                // Make sure the fileName is unique but only if chunking is disabled
                if (file_exists($uploadFolder . DIRECTORY_SEPARATOR . $fileName)) {
                    $ext = strrpos($fileName, '.');
                    $fileName_a = substr($fileName, 0, $ext);
                    $fileName_b = substr($fileName, $ext);

                    $count = 1;
                    while (file_exists($uploadFolder . DIRECTORY_SEPARATOR . $fileName_a . '_' . $count . $fileName_b))
                        $count++;

                    $fileName = $fileName_a . '_' . $count . $fileName_b;
                }

                $uploadFile = $uploadFolder . DIRECTORY_SEPARATOR . $fileName;
                $this->upload->saveAs($uploadFile); //Upload file thong qua object CUploadedFile

                $fileModel->name=$fileName;
                $fileModel->url='files/'.$fol.'/'.$fileName;
                $fileModel->contentId=$this->id;
                $fileModel->contentType=  File::TYPE_TOPIC;
                $fileModel->createTime=time();
                
                $fileModel->fileIsUnique=true;

                $fileModel->save();
            }

            parent::afterSave();
        }
        
        protected function afterDelete() {
            if($this->attachment){
                $this->attachment->delete();
            }
            
            parent::afterDelete();
        }
}